$(document).ready(function(){

var ajaxQueueArray = [];
var load = $('span#load').attr('url');

(function($) {

// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});

$.ajaxQueue = function( ajaxOpts ) {
	var jqXHR,
		dfd = $.Deferred(),
		promise = dfd.promise();

	// run the actual query
	function doRequest( next ) {
		jqXHR = $.ajax( ajaxOpts );
		jqXHR.done( dfd.resolve )
			.fail( dfd.reject )
			.then( next, next );
	}

	// queue our ajax request
	ajaxQueue.queue( doRequest );

	// add the abort method
	promise.abort = function( statusText ) {

		// proxy abort to the jqXHR if it is active
		if ( jqXHR ) {
			return jqXHR.abort( statusText );
		}

		// if there wasn't already a jqXHR we need to remove from queue
		var queue = ajaxQueue.queue(),
			index = $.inArray( doRequest, queue );

		if ( index > -1 ) {
			queue.splice( index, 1 );
		}

		// and then reject the deferred
		dfd.rejectWith( ajaxOpts.context || ajaxOpts, [ promise, statusText, "" ] );
		return promise;
	};

	return promise;
};

})(jQuery);


var run = {
	init:function(e,key){
		if(typeof e !== "undefined" || status == 'unprocessed'){
			jQuery.ajaxQueue({
				type: "POST",
				url: e.attr('url'),
				data:{
					option:e.val()
				}
			}).done(function(output){
				if(output == true){
					e.siblings('span.loading').html('<i class="icon-ok"></i>');
					e.prop('disabled', false);
					ajaxQueueArray[key] = {status : 'processed'};
				}else{
					e.siblings('span.loading').html('<i class="icon-remove"></i>');
				}
			}).fail(function(){
				e.siblings('span.loading').html('<i class="icon-warning-sign"></i>');
			});
		}
	},
	holder: function(e){
		var _holder ={
				status : 'unprocessed',
				ajaxObject : e
		};
		
		ajaxQueueArray.push(_holder);
	}
};

	$('.teacher-show-grades').on('change',function(){
		var lod = $('span#loader').attr('url');
		
		$(this).siblings('span.loading').html('<img src="'+lod+'">');
		$(this).prop('disabled', true);
		
		ajaxQueueArray = [];
		run.holder($(this));
		
			// loop
		$.each(ajaxQueueArray,function(i,e)
		{	
			run.init(e.ajaxObject,i,e.status);
		});
	});
});
